//
//  TMSearchController.m
//  国学培训用户端
//
//  Created by Tao Li on 2018/7/9.
//  Copyright © 2018年 mac. All rights reserved.
//

#import "TMSearchController.h"
#import "TMSearchReaultCell.h"
#import "TMSearchHeaderView.h"
#import "SPToolSet.h"
#import "TMHomeViewModel.h"
#import "TMShopHomeController.h"
#import "TMCommodityDetailController.h"
#import "TMSearchModel.h"
#import "TMHomePageController.h"
@interface TMSearchController ()<UICollectionViewDelegate,UICollectionViewDataSource>
@property (weak, nonatomic) IBOutlet UICollectionView *searchCollection;
@property (nonatomic, assign) CGSize itemSize;
@property (nonatomic, strong) TMSearchHeaderView *headerView;
@property (nonatomic, strong) TMHomeViewModel *viewModel;
@property (nonatomic, strong) NSArray *listArray;
@property (nonatomic, assign) BOOL isCourse;
@property (nonatomic, copy) NSString *keywords;
@property (nonatomic, assign) NSInteger pageNum;
@property (nonatomic, assign) NSInteger totalNum;
@property (nonatomic, strong) WZNoResultView *noResultView;
@end

@implementation TMSearchController
-(NSArray *)listArray{
    if (!_listArray) {
        _listArray = [NSArray array];
    }
    return _listArray;
}
-(void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    
}
- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    
}
- (void)viewDidLoad {
    [super viewDidLoad];
     self.title = @"搜索";
    self.pageNum = 1;
    [self registerNotications];
    self.searchCollection.keyboardDismissMode = UIScrollViewKeyboardDismissModeOnDrag;
    self.viewModel = [[TMHomeViewModel alloc]init];
    [self loadSearchData:@"1" AndAll:0 AndHigh:0];
    self.isCourse = NO;
}
- (void)loadSearchData:(NSString *)keywords AndAll:(NSInteger)isAll AndHigh:(NSInteger)high{
    NSMutableDictionary *dic = [NSMutableDictionary dictionary];
    if (isAll == 0) {
        //全部
        self.isCourse = NO;
        [dic setValue:@"1" forKey:@"type"];
        [dic setValue:self.keywords forKey:@"key"];
    }
    if (isAll == 1) {
        //关键字
        [dic setValue:keywords forKey:@"key"];
    }
    if (isAll == 2) {
        //店铺
         self.isCourse = YES;
        [dic setValue:@"2" forKey:@"type"];
        [dic setValue:self.keywords forKey:@"key"];
    }
    if (isAll == 3) {
        //价格
         self.isCourse = NO;
        [dic setValue:@(high) forKey:@"price"];
        [dic setValue:self.keywords forKey:@"key"];
    }
    if (isAll == 4) {
        //销售量
         self.isCourse = NO;
        [dic setValue:@(high) forKey:@"sale"];
        [dic setValue:self.keywords forKey:@"key"];
    }
    TMHomePageController * vc = (id)self.navigationController.childViewControllers.firstObject;
    NSString * degree = [NSString stringWithFormat:@"[%@,%@]",vc.latitude,vc.longitude];
    [dic setObject:degree forKey:@"degree"];
    self.searchCollection.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        self.pageNum = 1;
        [dic setValue:@(self.pageNum) forKey:@"page"];
        [self.viewModel getSearchDataWithKwords:dic Success:^(id responseObject,id total) {
            self.totalNum = [total integerValue];
            self.listArray = responseObject;
            [self noResultViewShowORNot];
            [self.searchCollection reloadData];
            [self.searchCollection.mj_header endRefreshing];
            [self.searchCollection.mj_footer endRefreshing];
        } failed:^(NSString *error) {
            [self noResultViewShowORNot];
            [self.searchCollection reloadData];
            [self.searchCollection.mj_header endRefreshing];
            [self.searchCollection.mj_footer endRefreshing];
        }];
    }];
    self.searchCollection.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingBlock:^{
        self.pageNum ++;
        if (self.pageNum > self.totalNum) {
            [self.searchCollection.mj_footer endRefreshingWithNoMoreData];
            return;
        }
        [dic setValue:@(self.pageNum) forKey:@"page"];
        [self.viewModel getSearchDataWithKwords:dic Success:^(id responseObject,id total) {
            self.listArray = responseObject;
            [self.searchCollection reloadData];
            [self.searchCollection.mj_header endRefreshing];
            [self.searchCollection.mj_footer endRefreshing];
        } failed:^(NSString *error) {
            [self.searchCollection reloadData];
            if (self.pageNum > 1) {
                self.pageNum--;
            }
            [self.searchCollection.mj_header endRefreshing];
            [self.searchCollection.mj_footer endRefreshing];
        }];
    }];
    [self.searchCollection.mj_header beginRefreshing];
}
- (void)registerNotications{
    //ALLSEARCHNOTI BUSSINESSSEARCHNOTI PRICESEARCHNOTI SALESEARCHNOTI
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(gegainSearch:) name:@"BEGAINSEARCHNOTI" object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(AllSearch:) name:@"ALLSEARCHNOTI" object:nil];
}
- (void)setSearchCollection:(UICollectionView *)searchCollection{
    _searchCollection = searchCollection;
    [_searchCollection registerNib:[UINib nibWithNibName:@"TMSearchReaultCell" bundle:nil] forCellWithReuseIdentifier:@"TMSearchReaultCell"];
    [_searchCollection registerClass:[TMSearchHeaderView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"TMSearchHeaderView"];
    _searchCollection.delegate = self;
    _searchCollection.dataSource = self;
    UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc]init];
    flowLayout.minimumLineSpacing = 12;
    flowLayout.minimumInteritemSpacing = 0;
    _itemSize = CGSizeMake(173 * kWindowW /375, 210* kWindowW /375);
    _searchCollection.collectionViewLayout = flowLayout;
}
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{
    return self.itemSize;
}
- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section {
    return UIEdgeInsetsMake(12, 12, 0, 12);
}
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    return self.listArray.count;
}

- (__kindof UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    TMSearchReaultCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"TMSearchReaultCell" forIndexPath:indexPath];
    cell.isCourse = self.isCourse;
    cell.model = self.listArray[indexPath.row];
    return cell;
}
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    
    TMSearchModel *model = self.listArray[indexPath.row];
    if (self.isCourse == YES) {
        //jigou
        TMShopHomeController *vc = [[UIStoryboard storyboardWithName:@"Nearby" bundle:nil] instantiateViewControllerWithIdentifier:@"TMShopHomeController"];
        vc.shopid = model.sid;
        [self.navigationController pushViewController:vc animated:YES];
    }else{
        TMCommodityDetailController *vc = [[UIStoryboard storyboardWithName:@"Nearby" bundle:nil] instantiateViewControllerWithIdentifier:@"TMCommodityDetailController"];
        vc.rid = model.sid;
        [self.navigationController pushViewController:vc animated:YES];
    }
}
#pragma mark -  header
//要先设置表头高度
-(CGSize)collectionView:(UICollectionView*)collectionView layout:(UICollectionViewLayout*)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section
{
    CGSize size = {kWindowW, 120*kWindowW/375};
    return size;
}

//在表头内添加内容,需要创建一个继承collectionReusableView的类,用法类比tableViewcell
- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath
{
    // 初始化表头
    _headerView = (TMSearchHeaderView*)[collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"TMSearchHeaderView" forIndexPath:indexPath];
    //__weak typeof(self) weakself = self;
    return _headerView;
}
#pragma --mark search
- (void)gegainSearch:(NSNotification *)noti{
    [self listArray];
    NSString *key = noti.userInfo[@"text"];
    if (key == nil || key.length <=0) {
        [TMProgressHUD showInfoWithStyleDarkStatus:@"搜索关键字不能为空!"];
        return;
    }
    self.keywords = key;
    [self loadSearchData:self.keywords AndAll:1 AndHigh:0];

}
- (void)AllSearch:(NSNotification *)noti{
    [self listArray];
    NSInteger index = [noti.userInfo[@"index"]integerValue];
    NSInteger tag = [noti.userInfo[@"tag"]integerValue];
    //1 2 3 4
    if (index == 1) {
       //ke cheng
        [self loadSearchData:@"1" AndAll:0 AndHigh:0];
    }
    if (index == 2) {
        //店铺。
        [self loadSearchData:@"2" AndAll:2 AndHigh:0];
    }
    if (index == 3) {
        //price。gao  di?? 10 11
        if (tag == 10) {
             [self loadSearchData:@"1" AndAll:3 AndHigh:1];
        }
        if (tag == 11) {
            [self loadSearchData:@"2" AndAll:3 AndHigh:2];
        }
    }
    if (index == 4) {
        //sale。 gao  di??
        if (tag == 20) {
            [self loadSearchData:@"1" AndAll:4 AndHigh:1];
        }
        if (tag == 21) {
            [self loadSearchData:@"2" AndAll:4 AndHigh:2];
        }
    }

}
- (WZNoResultView *)noResultView{
    if (!_noResultView) {
        _noResultView = [[[NSBundle mainBundle] loadNibNamed:@"WZNoResultView" owner:nil options:nil]firstObject];
        if (kWindowH == 812.0) {
            _noResultView.frame = CGRectMake(0, 120*kWindowW/375, kWindowW, kWindowH-120*kWindowW/375);
        }else {
            _noResultView.frame = CGRectMake(0, 120*kWindowW/375, kWindowW, kWindowH-120*kWindowW/375);
        }
        _noResultView.isSearchVC = YES;
        [self.searchCollection addSubview:_noResultView];
    }
    return _noResultView;
}
- (void)noResultViewShowORNot{
    if (!self.listArray.count) {
        self.noResultView.hidden = NO;
    }else{
        self.noResultView.hidden = YES;
    }
}
@end
